package stz.flash.main.strobe.model;

import stz.flash.main.FlashKeyEvent;
import stz.flash.main.ScreenHandle;
import stz.flash.option.Option;
import net.rim.device.api.system.Application;


public class VRFlashController {
	
	private static final int REPEAT_NUM_POST_SPACE = 4;
	public static final int DELAY_BEFORE_INIT_INSPECT_FLASH = 50;
	private static final int DELAY_AFTER_POST_SPACE = 50;
	
	private static final int REPEAT_NUM_INSPECT_FLASH = 25;
	private static final int DELAY_INSPECT_FLASH = 20;

	private static final int DELAY_AFTER_POPSCREEN = 40;
	private static final int DELAY_AFTER_PUSHSCREEN = 40;
	
	public static void reverseAndApplyVRFlashStateOfOption(){
		reverseVRFlashStateOfOption();
		applyVRFlashStateOfOption();
	}
	private static void reverseVRFlashStateOfOption() {
		Option.getIns().setVRFlashState(!Option.getIns().isVRFlashState());
	}
	
	
	public static void applyVRFlashStateOfOption() {
		popScreen();
		applyOption();
		pushScreen();
	}
	private static void applyOption(){
		try {

			InspectVRFlash.waitVisibleVR();

			if (sameCurrentVRFalshStateAndVRFlashStateOfOption()) 
				return;

			for (int i = 0; i < REPEAT_NUM_POST_SPACE; i++){

				postSpaceKey();
				Thread.sleep(DELAY_AFTER_POST_SPACE);

				for (int j = 0; j < REPEAT_NUM_INSPECT_FLASH; j++) {

					if (sameCurrentVRFalshStateAndVRFlashStateOfOption()) 
						return;
					Thread.sleep(DELAY_INSPECT_FLASH);
				}
			}

		} catch (InterruptedException e1) {
		}
	}
	private static boolean sameCurrentVRFalshStateAndVRFlashStateOfOption() {
		return isCurrentVRFlashState() == isVRFlashStateOfOption();
	}
	private static boolean isCurrentVRFlashState() {
		return InspectVRFlash.isFlashState();
	}
	private static boolean isVRFlashStateOfOption() {
		return Option.getIns().isVRFlashState();
	}
	private static void postSpaceKey() {
		FlashKeyEvent.postSpaceKey();
	}
	
	public static void popScreen() {
		
		if (ScreenHandle.getIns().isDisplayed() == true) {
		
			synchronized (Application.getEventLock()) {
				ScreenHandle.getIns().popScreen();
			}
		}
		try {
			Thread.sleep(DELAY_AFTER_POPSCREEN);
		} catch (InterruptedException e) {
		}
	}
	
	private static void pushScreen() {
		
		if (ScreenHandle.getIns().isDisplayed() == false) {

			synchronized (Application.getEventLock()) {
				ScreenHandle.getIns().pushScreen();
			}
		}
		try {
			Thread.sleep(DELAY_AFTER_PUSHSCREEN);
		} catch (InterruptedException e) {
		}
	}
}